package com.cdream.basic.thread.pool;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * forkjoin线程池案例
 */
public class ForkJoinPoolExample {
    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool(4);
        System.out.println(forkJoinPool.invoke(new Adder(0, 4)));
        // forkJoinPool.shutdown();
    }

    static class Adder extends RecursiveTask<Integer> {
        private int start;
        private int end;

        public Adder(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            if (start==end) {
                return start;
            }
            if (end-start==1){
                return start+end;
            }
            int mid = start + (end - start) >> 1;
            Adder adder = new Adder(start, mid);
            adder.fork();
            Adder adder3 = new Adder(mid + 1, end);
            adder3.fork();

            Integer adder1 = adder.join();
            Integer adder2 = adder3.join();
            return adder1 + adder2;
        }
    }
}
